package com.jung.net.interceptor

import com.beyond.common.util.AppUtils
import com.beyond.common.util.NetWorkUtil
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @author chenshiyang
 * @time 2022/6/23 17:46
 * @name CacheInterceptor.kt
 * @class describe
 */
class CacheInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (!NetWorkUtil.isNetworkAvailable(AppUtils.instance)) {
            request = request.newBuilder()
                .cacheControl(CacheControl.FORCE_CACHE)
                .build()
        }
        val response = chain.proceed(request)
        val maxAge = 60
        // 有网络时 设置缓存超时时间0个小时 ,意思就是不读取缓存数据,只对get有用,post没有缓冲
        response.newBuilder()
            .removeHeader("pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
            .header("Cache-Control", "public, max-age=$maxAge")
            .build()
        return response
    }
}